<?php

namespace app\admin\controller;

use app\admin\model\Config;
use app\admin\model\member\Bill;
use app\common\controller\Backend;

/**
 * 用户管理
 */
class Member extends Backend
{
    /**
     * Member模型对象
     * @var object
     * @phpstan-var \app\admin\model\Member
     */
    protected object $model;

    protected array|string $preExcludeFields = ['id', 'create_time'];

    protected string|array $quickSearchField = ['id'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\Member();
    }


    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void
    {
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);
        $default_avatar = (new Config())->where(['name' => 'avatar'])->value('value');
        foreach ($res as $value) {
            if (!$value['avatar']) {
                $value['avatar'] = env('domain.image_url') . $default_avatar;
            }
        }

        $this->success('', [
            'list' => $res->items(),
            'total' => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }


    /**
     * 编辑
     * @throws Throwable
     */
    public function edit(): void
    {
        $pk = $this->model->getPk();
        $id = $this->request->param($pk);
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }
            $data = $this->excludeFields($data);
            if($data['integral'] > $row['residue_integral']){
                $this->error('扣除积分大于用户剩余积分');
            }
            $result = false;
            $this->model->startTrans();
            try {
                (new \app\api\model\Bill())->addBill($row, $data['integral'], $data['title'], 2);
                $result = $this->model->where(['id' => $row['id']])->setDec('residue_integral', $data['integral']);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }

        $this->success('', [
            'row' => $row
        ]);
    }


    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */
}